import { errorRouterMap } from '@/router'
import componentConfig from '@/utils/config.view.router'

// 设置权限路由
const GENERATE_ROUTERS = 'permission/GENERATE_ROUTERS'
// 清除权限路由
const CLEAR_ROUTERS = 'permission/CLEAR_ROUTERS'

/**
 * 递归构建前端路由配置
 * @param tree
 */
function filterAsyncRouter(tree) {
  return tree.map((item, key) => {
    const _router = {
      path: '/' + item.routerName,
      name: item.name + (item.routerName === 'default' && '_' + key),
      icon: item.icon,
      isShow: item.isMenu,
      routerUrl: item.routerUrl,
      routerParameter: item.routerParameter,
      component: item.isChild === '1' && componentConfig[item.routerName] ? componentConfig[item.routerName] : componentConfig.layout,
      meta: {
        title: item.name,
        parames: item.routerParameterDescribe
      },
      children: item.children && filterAsyncRouter(item.children)
    }
    // 判断是否是子菜单，是就让父级跳到子菜单，routerUrl字段在后台设置
    if (item.routerUrl || item.children.length > 1) {
      _router.redirect = item.routerUrl
    }
    return _router
  })
}

// initial state
const state = {
  routers: [],
  extendRoutes: []
}

// getters
const getters = {
  extendRoutes: state => state.extendRoutes,
  routers: state => state.routers
}

// actions
const actions = {
  generateRoutes({ commit }, tree) {
    return new Promise(resolve => {
      const accessedRouters = filterAsyncRouter(tree)
      commit(GENERATE_ROUTERS, accessedRouters)
      resolve()
    })
  },
  clearPermissionRouter({ commit }) {
    commit(CLEAR_ROUTERS)
  }
}
// mutations
const mutations = {
  [GENERATE_ROUTERS](state, routers) {
    state.extendRoutes = routers.concat(errorRouterMap)
    state.routers = routers
  },
  [CLEAR_ROUTERS](state) {
    state.routers = []
    state.extendRoutes = []
  }
}

export default {
  state,
  getters,
  actions,
  mutations
}
